/**
 * 登录处理逻辑
 */
import { request } from "./request";
import { useUserStore } from "@/store";

// 检查登录状态
export const checkLogin = () => {
    const accessToken = uni.getStorageSync("accessToken");
    return !!accessToken;
};

// 获取token
export const getToken = () => {
    return uni.getStorageSync("accessToken") || "";
};

// 微信登录 - 支持用户端和商家端登录
export const weixinLogin = async (role = "user", params = {}) => {
    try {
        // 步骤1: 调用微信登录接口获取code
        const { code } = await uni.login({
            provider: "weixin",
        });

        console.log("code:", code);
        let userInfo = null;

        // 步骤2: 发送所有信息到后端换取token
        const res = await request({
            url: "/wechat-auth/login",
            method: "POST",
            data: {
                code,
                nickname: params.nickname || '微信用户',
                avatarUrl: params.avatarUrl,
                phoneCode: params.phoneCode || null,
            },
            loading: false, // 避免重复显示loading
        });

        console.log('登录返回结果', res)
        // 修改这里的逻辑，适配新的返回数据结构
        if (res.code === 200 && res.data && res.data.token) {

            // 存储accessToken
            uni.setStorageSync("accessToken", res.data.token);
            console.log('accessToken已存储:', res.data.token);

            // 存储token过期时间 - 使用timestamp作为过期时间
            if (res.timestamp) {
                const expireTimeMs = res.timestamp;
                console.log("expireTimeMs", expireTimeMs);
                uni.setStorageSync(
                    "tokenExpireTime",
                    new Date(expireTimeMs).toISOString()
                );
            }
            const phone = res.data.userInfo?.phone || '';
            //3.根据手机号去后端查询用户信息
            const respone = await request({
                url: '/wechat-user/phone',
                method: 'GET',
                data: { phone }
            })
            console.log("根据手机号去后端查询用户信息", respone);

            // 存储用户信息
            if (respone.code === 200 && respone.data) {
                console.log("存储用户信息:", respone.data);
                respone.data.openid = ''; // 清空openid，避免泄露
                uni.setStorageSync("userInfo", respone.data);
            }
            // 更新store中的角色和token
            const userStore = useUserStore();
            userStore.setToken(res.data.token);
            // 优先使用后端返回的用户角色
            if (res.data.userInfo?.role) {
                userStore.setRole(res.data.userInfo.role);
            } else if (role) {
                userStore.setRole(role);
            }

            return true;
        } else {
            // 处理返回数据不完整的情况
            console.error("登录响应数据不完整:", res);
            uni.showToast({
                title: res.message || "登录失败，返回数据异常",
                icon: "none",
            });
            return false;
        }
    } catch (error) {
        console.error("登录失败:", error);
        uni.showToast({
            title: "登录失败，请重试",
            icon: "none",
        });
        return false;
    }
};

// 退出登录
export const logout = () => {
    // 清除本地存储的token和用户信息
    uni.removeStorageSync("accessToken");
    uni.removeStorageSync("tokenExpireTime");
    uni.removeStorageSync("userInfo");

    // 更新store
    const userStore = useUserStore();
    userStore.setToken("");
    userStore.setRole("user");

    // 跳转到登录页面
    uni.reLaunch({
        url: "/public/login/login",
    });
};



// 调试函数：检查token状态
export const debugTokenStatus = () => {
    const accessToken = uni.getStorageSync("accessToken");
    const tokenExpireTime = uni.getStorageSync("tokenExpireTime");

    console.log("=== Token状态调试信息 ===");
    console.log("accessToken:", accessToken ? `${accessToken.substring(0, 20)}...` : "无");
    console.log("tokenExpireTime:", tokenExpireTime);
    console.log("当前时间:", new Date().toISOString());

    if (tokenExpireTime) {
        const expireTime = new Date(tokenExpireTime);
        const now = new Date();
        const timeDiff = expireTime.getTime() - now.getTime();
        console.log("token剩余时间（毫秒）:", timeDiff);
        console.log("token剩余时间（分钟）:", Math.floor(timeDiff / 60000));
    }

    console.log("========================");
};
